package com.ec50n9.server.module.ebookCategory

import com.ec50n9.server.common.mayBeNotFound
import com.ec50n9.server.common.render
import com.ec50n9.server.module.common.BaseService
import com.ec50n9.server.module.common.renderTo
import io.swagger.v3.oas.annotations.Operation
import io.swagger.v3.oas.annotations.tags.Tag
import org.springframework.data.repository.CrudRepository
import org.springframework.stereotype.Service
import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.*
import java.util.*

interface EbookCategoryRepository : CrudRepository<EbookCategory, String> {

    fun findByCode(code: String): Optional<EbookCategory>
}

@Service
class EbookCategoryService(private val ebookCategoryRepository: EbookCategoryRepository) :
    BaseService<EbookCategory, String>("书本分类", ebookCategoryRepository) {
    fun findOneByCode(code: String): EbookCategory = mayBeNotFound(name) {
        ebookCategoryRepository.findByCode(code).orElseThrow()
    }
}

@Tag(name = "书本分类管理")
@RestController
@RequestMapping("/api/ebook-categorys")
class EbookCategoryController(private val ebookCategoryService: EbookCategoryService){

    @Operation(summary = "获取全部")
    @GetMapping
    fun findAll(): List<EbookCategoryQueryRendered> =
        ebookCategoryService.findAll().renderTo(EbookCategoryQueryRendered::class.java)

    @Operation(summary = "通过code获取")
    @GetMapping("/{code}")
    fun findOne(@PathVariable code: String): EbookCategoryQueryRendered =
        ebookCategoryService.findOneByCode(code).renderTo(EbookCategoryQueryRendered::class.java)

    @Operation(summary = "新建")
    @PostMapping
    fun newOne(@RequestBody @Validated createForm: EbookCategoryCreateForm): EbookCategoryQueryRendered {
        val ebookCategory = EbookCategory("", "")
        createForm.render(ebookCategory)
        return ebookCategoryService.newOne(ebookCategory).renderTo(EbookCategoryQueryRendered::class.java)
    }

    @Operation(summary = "更新")
    @PatchMapping("/{code}")
    fun update(
        @RequestBody updateForm: EbookCategoryUpdateForm,
        @PathVariable code: String
    ): EbookCategoryQueryRendered {
        val ebookCategory = ebookCategoryService.findOneByCode(code)
        updateForm.render(ebookCategory, true)
        return ebookCategoryService.update(ebookCategory).renderTo(EbookCategoryQueryRendered::class.java)
    }

    @Operation(summary = "删除")
    @DeleteMapping("/{code}")
    fun delete(@PathVariable code: String) = with(ebookCategoryService){
        delete(findOneByCode(code))
    }
}